package com.sdhs.costcontrol.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

import com.sdhs.common.core.domain.event.ProcessEvent;
import com.sdhs.common.enums.BusinessStatusEnum;
import com.sdhs.myproject.domain.GcMyprojectContractInformation;
import com.sdhs.myproject.domain.GcMyprojectInformation;
import com.sdhs.myproject.domain.GcMyprojectProfitMarginMeasurement;
import com.sdhs.myproject.mapper.GcMyprojectProfitMarginMeasurementMapper;
import com.sdhs.myproject.service.IGcMyprojectContractInformationService;
import com.sdhs.projectschedule.domain.GcProgressCompletionOn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sdhs.businessfile.domain.BusinessFile;
import com.sdhs.businessfile.service.IBusinessFileService;
import com.sdhs.common.enums.BusinessTypeEnum;
import com.sdhs.common.utils.DateUtils;
import com.sdhs.common.utils.SecurityUtils;
import com.sdhs.costcontrol.domain.GcControlSettlementPayment;
import com.sdhs.costcontrol.mapper.GcControlSettlementPaymentMapper;
import com.sdhs.costcontrol.service.IGcControlSettlementPaymentService;

/**
 * 项目结算Service业务层处理
 * 
 * @author wanglei
 * @date 2025-03-10
 */
@Service
public class GcControlSettlementPaymentServiceImpl implements IGcControlSettlementPaymentService 
{
    @Autowired
    private GcControlSettlementPaymentMapper gcControlSettlementPaymentMapper;
    
    @Autowired
    private IBusinessFileService businessFileService;
    @Autowired
    private IGcMyprojectContractInformationService myprojectContractInformationService;

    @Autowired
    private GcMyprojectProfitMarginMeasurementMapper gcMyprojectProfitMarginMeasurementMapper;

    /**
     * 查询项目结算
     * 
     * @param id 项目结算主键
     * @return 项目结算
     */
    @Override
    public GcControlSettlementPayment selectGcControlSettlementPaymentById(Long id)
    {
    	GcControlSettlementPayment controlSettlementPayment = gcControlSettlementPaymentMapper.selectGcControlSettlementPaymentById(id);
    	List<BusinessFile> fileList = businessFileService.listByBusinessTypeAndId(BusinessTypeEnum.GC_CONTROL_SETTLEMENT_PAYMENT.getCode(), String.valueOf(id));
    	controlSettlementPayment.setFileList(fileList);
    	return controlSettlementPayment;
    }

    /**
     * 查询项目结算列表
     * 
     * @param gcControlSettlementPayment 项目结算
     * @return 项目结算
     */
    @Override
    public List<GcControlSettlementPayment> selectGcControlSettlementPaymentList(GcControlSettlementPayment gcControlSettlementPayment)
    {
        return gcControlSettlementPaymentMapper.selectGcControlSettlementPaymentList(gcControlSettlementPayment);
    }

    /**
     * 新增项目结算
     * 
     * @param gcControlSettlementPayment 项目结算
     * @return 结果
     */
    @Override
    public GcControlSettlementPayment insertGcControlSettlementPayment(GcControlSettlementPayment gcControlSettlementPayment)
    {
        gcControlSettlementPayment.setApprovalStatus(BusinessStatusEnum.DRAFT.getStatusValue());
    	gcControlSettlementPayment.setCreater(SecurityUtils.getUsername());
        gcControlSettlementPayment.setCreateTime(DateUtils.getNowDate());
        gcControlSettlementPaymentMapper.insertGcControlSettlementPayment(gcControlSettlementPayment);
        /*新增结算的时候将结算值同步到我的项目-利润率-交工利润率*/
        /*handler(gcControlSettlementPayment);*/
        /*新增文件*/
        businessFileService.saveFileBatch(BusinessTypeEnum.GC_CONTROL_SETTLEMENT_PAYMENT.getCode(), String.valueOf(gcControlSettlementPayment.getId()), gcControlSettlementPayment.getFileList());
        return gcControlSettlementPayment;
    }

    /**
     * 修改项目结算
     * 
     * @param gcControlSettlementPayment 项目结算
     * @return 结果
     */
    @Override
    public int updateGcControlSettlementPayment(GcControlSettlementPayment gcControlSettlementPayment)
    {
    	gcControlSettlementPayment.setUpdater(SecurityUtils.getUsername());
        gcControlSettlementPayment.setUpdateTime(DateUtils.getNowDate());
        int result = gcControlSettlementPaymentMapper.updateGcControlSettlementPayment(gcControlSettlementPayment);
        /*修改结算的时候将结算值同步到我的项目-利润率-交工利润率*/
        /*handler(gcControlSettlementPayment);*/
        businessFileService.saveFileBatch(BusinessTypeEnum.GC_CONTROL_SETTLEMENT_PAYMENT.getCode(), String.valueOf(gcControlSettlementPayment.getId()), gcControlSettlementPayment.getFileList());
		return result;
    }

    /**
     * 批量删除项目结算
     * 
     * @param ids 需要删除的项目结算主键
     * @return 结果
     */
    @Override
    public int deleteGcControlSettlementPaymentByIds(Long[] ids)
    {
        return gcControlSettlementPaymentMapper.deleteGcControlSettlementPaymentByIds(ids);
    }

    /**
     * 删除项目结算信息
     * 
     * @param id 项目结算主键
     * @return 结果
     */
    @Override
    public int deleteGcControlSettlementPaymentById(Long id)
    {
        return gcControlSettlementPaymentMapper.deleteGcControlSettlementPaymentById(id);
    }

    public void handler(GcControlSettlementPayment gcControlSettlementPayment) {
        GcMyprojectProfitMarginMeasurement gcMyprojectProfitMarginMeasurement = new GcMyprojectProfitMarginMeasurement();
        gcMyprojectProfitMarginMeasurement.setProjectId(gcControlSettlementPayment.getProjectId());

        /*获取结算值*/
        BigDecimal settlementValue = gcControlSettlementPayment.getSettlementValue();
        GcMyprojectContractInformation all = myprojectContractInformationService.getAll(new Long[]{gcControlSettlementPayment.getProjectId()});

        // 处理可能的 null 值，默认给 0
        BigDecimal managementMoney = all.getManagementMoney() != null ? all.getManagementMoney() : BigDecimal.ZERO; // 成本控制总数
        BigDecimal totalPayMoney = all.getTotalPayMoney() != null ? all.getTotalPayMoney() : BigDecimal.ZERO; // 累计支付金额

        // 计算 moneyOver = ((settlementValue - managementMoney - totalPayMoney) / settlementValue) * 100
        BigDecimal moneyOver = settlementValue
                .subtract(managementMoney)
                .subtract(totalPayMoney)
                .divide(settlementValue, 10, RoundingMode.HALF_UP)  // 防止除零，并设置精度
                .multiply(new BigDecimal(100))
                .setScale(2, RoundingMode.HALF_UP);  // 保留2位小数并四舍五入

        /*交工利润率*/
        gcMyprojectProfitMarginMeasurement.setHandoverUtilization(moneyOver.toString());
        gcMyprojectProfitMarginMeasurementMapper.updateMeasurement(gcMyprojectProfitMarginMeasurement);
    }


    /**
     *项目结算审批监听
     * 审批完成之后修改我的项目交工利润率
     */
    @org.springframework.context.event.EventListener(condition = "#processEvent.key.startsWith('project_cost')")
    public void processHandler(ProcessEvent processEvent) {

        // 已完成（已通过）
        if (BusinessStatusEnum.FINISH.getStatus().equals(processEvent.getStatus())) {
            String businessKey = processEvent.getBusinessKey();
            GcControlSettlementPayment gcControlSettlementPayment = gcControlSettlementPaymentMapper.selectSettlementByInstanceId(businessKey);
            /*调用修改我的项目竣工利润率*/
            handler(gcControlSettlementPayment);
        }

    }
}
